#include "constants.h";

XfMissionChapterExecute={
	private ["_chapter_succeeded"];
	diag_log "";
	diag_log "=========================================================================";
	diag_log "                             CHAPTER 1                                   ";
	diag_log "=========================================================================";
	diag_log "";
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Starting Chapter","_last_random_reinforcement","_random_reinf_diff","_reinforcement_power","_vgrp","_wp"];
	DM_Mission_ArtilleryVariables = [];
	DM_Mission_Chapter_CanRun = True;
	DM_Mission_Chapter_Runs = True;
	DM_Mission_Chapter_Success = 0;
	call XfMissionChapterSetup;
	_chapter_succeeded = false;
	if (!DM_Mission_Mission_CanRun) exitWith {diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Mission canceled!"];};
	
	_convoy_started = false;
	_convoy_alive = true;
	_convoy_arrived = false;
	_random_town = DM_Chapter_Location;
	_random_end = DM_Chapter_LocationEnd;
	_random_town_pos = _random_town select XF_MAP_LOCATION_CENTER;
	_random_end_pos = _random_end select XF_MAP_LOCATION_CENTER;
	_vec_list = DM_VIP;
	_fnc_convoy = compile PreprocessFileLineNumbers "scripts\sideconvoy.sqf";
	
	diag_log Format["(%1)[%2]: %3: %4: %5, %6",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Entering the loop",[_convoy_alive,_convoy_arrived,_vec_list], Time];
	while {DM_Mission_Chapter_CanRun AND DM_Mission_Mission_CanRun} do {
		sleep 10;
		if (d_mission_debug_messages) then { diag_log Format["(%1)[%2]: %3: %4: %5, %6",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Entering the loop",[_convoy_alive,_convoy_arrived,_vehicles,_drivers], Time]; };
		
		if (!_convoy_started) then {
			_convoy_started = true;
			_convoy_arrived = [_random_town_pos, _random_end_pos, [_random_town_pos, _random_end_pos] call XfDirTo, _vec_list] call _fnc_convoy;
		};
		
		if (_convoy_arrived) then {
			["StopConvoy","", "","",[],"Failed"] call XfMissionTask;
			_chapter_succeeded = false;
			DM_Mission_Chapter_CanRun = false;
		};
		if (!_convoy_arrived) then {
			["StopConvoy","", "","",[],"Succeeded"] call XfMissionTask;
			_chapter_succeeded = true;
			DM_Mission_Chapter_CanRun = false;
		};
	};
	
	if (DM_Mission_Mission_CanRun) then {
		if (_chapter_succeeded) then {
			call XfMissionChapterSuccess;
		} else {
			call XfMissionChapterFailure;
		};
	} else {
		diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Mission canceled!"];
	};

	// Just in case a reinforcement is already on the way.
	call XfMissionCancelReinforcement;
	call XfMissionChapterCleanUp;
	DM_Mission_Chapter_Runs = False;
};

XfMissionChapterSetup={
	private ["_random_town","_random_town_pos","_random_town_size","_troops_power","_troops_coeff","_grpSoldiers","_grpVehicle","_i","_vgrp","_wp"];
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Starting Initialization"];
	
	_map_center = getArray (configFile>>"CfgWorlds">>worldName >> "centerPosition");
	_minimum_dist = (((_map_center select 0) max (_map_center select 1)) * 0.5);
	
	_random_town = [];
	_random_end = [];
	_i_tries = 40;
	_current_dist = 0;
	while { (count _random_town <= 0) && (_i_tries > 0) } do {
		_random_town = [true] call XfMissionGetRandomTown;
		diag_log Format["(%1)[%2]: %3: %4 %5",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Testing Start:",_random_town];
		if (count _random_town > 0) then {
			_random_town_pos = _random_town select XF_MAP_LOCATION_CENTER;
			_random_town_size = _random_town select XF_MAP_LOCATION_SIZE;
			if ((_random_town_pos distance FLAG_BASE) < 700) then {
				_random_town = [];
			} else {
				_random_end = [];
				_i_tries2 = 20;
				while { (_i_tries2 > 0) } do {
					_random_end_test = [true] call XfMissionGetRandomTown;
					diag_log Format["(%1)[%2]: %3: %4 %5",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Testing End:",_random_end_test];
					if (count _random_end_test > 0) then {
						_random_end_pos = _random_end_test select XF_MAP_LOCATION_CENTER;
						if ((_random_end_pos distance _random_town_pos) > _minimum_dist || (_random_end_pos distance _random_town_pos) > _current_dist) then {
							_current_dist = (_random_end_pos distance _random_town_pos);
							_random_end = _random_end_test;
						};
					};
					_i_tries2 = _i_tries2 - 1;
				};
				if ((count _random_end) <= 0) then { _random_town = []; };
			};
		};
		_i_tries = _i_tries - 1;
	};
	if ((count _random_town) <= 0) exitWith {"Could not pick a random town" call XfMissionMessageToAll; DM_Mission_Mission_CanRun = false; DM_Mission_Chapter_CanRun = false;};
	_random_end_pos = _random_end select XF_MAP_LOCATION_CENTER;
	DM_Chapter_Location = _random_town;
	DM_Chapter_LocationEnd = _random_end;
	
	_random_town_name = _random_town select XF_MAP_LOCATION_DISPLAYNAME;
	_random_end_name = _random_end select XF_MAP_LOCATION_DISPLAYNAME;
	diag_log Format["(%1)[%2]: %3: %4 %5 / %6",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Selected Towns:",_random_town, _random_end];
	
	// This indicates where the mission takes place
	[_random_town_pos,_random_town_size,_random_town_name] call XfMissionCurrentPosition;
	
	// Spawn the convoy vehicles.
	// ["T90","T72_RU"],
	// ["BMP3","BRDM2_INS","BMP2_INS","BTR90"],
	// ["BTR90","BRDM2_INS","BRDM2_ATGM_INS"],
	// ["Ural_ZU23_INS","2S6M_Tunguska","Ural_ZU23_INS","ZSU_INS","Ural_ZU23_INS"],
	// ["GAZ_Vodnik","GAZ_Vodnik_HMG","Ural_ZU23_INS"],
	// ["UAZ_MG_INS","UAZ_AGS30_RU","UAZ_MG_INS","UAZ_AGS30_INS","UAZ_MG_INS","UAZ_SPG9_INS","UAZ_MG_INS"],
	// ["KORD","AGS_RU","DSHKM_Ins","2b14_82mm","KORD_high","Metis","DSHkM_Mini_TriPod","SPG9_Ins"],
	// ["ZU23_Ins","Igla_AA_pod_East","ZU23_CDF"],
	// ["D30_RU","GRAD_RU"],
	// ["KamazRefuel"],
	// ["KamazRepair"],
	// ["KamazReammo"]
	_enemy_side_char = switch (d_enemy_side) do {case "EAST": {"E"};case "WEST": {"W"};case "GUER": {"G"};case "CIV": {"G"}; default{"E"};};

	_vehicle_array = missionNamespace getVariable format ["d_veh_a_%1",_enemy_side_char];
	_vec_list = [];
	// One heavy APCs
	_vec_list set [ count _vec_list, ((_vehicle_array select XF_VEHICLE_TYPES_HEAVYAPC) call XfRandomArrayVal)];
	// One light APCs
	_vec_list set [ count _vec_list, ((_vehicle_array select XF_VEHICLE_TYPES_LIGHTAPC) call XfRandomArrayVal)];
	// One Ammo Truck
	_vec_list set [ count _vec_list, ((_vehicle_array select XF_VEHICLE_TYPES_AMMO) call XfRandomArrayVal)];
	// One Light Wheeled
	_vec_list set [ count _vec_list, ((_vehicle_array select XF_VEHICLE_TYPES_LIGHTWHEEL) call XfRandomArrayVal)];
	// Second Ammo Truck
	_vec_list set [ count _vec_list, ((_vehicle_array select XF_VEHICLE_TYPES_AMMO) call XfRandomArrayVal)];
	// One Heavy Wheeled
	_vec_list set [ count _vec_list, ((_vehicle_array select XF_VEHICLE_TYPES_HEAVYWHEEL) call XfRandomArrayVal)];
	
	DM_VIP = _vec_list;

	[false,["chapter1_start_cross",_random_town_pos, "ICON", "ColorRed", [1,1],"Start",20,"hd_destroy","",0.8]] call XfMissionMarker;
	[false,["chapter1_end_cross",_random_end_pos, "ICON", "ColorRed", [1,1],"End",20,"hd_destroy","",0.8]] call XfMissionMarker;
	
	// We search a spot to place the teleporter which is around the town on a road (to avoid mountains and forests)
	_teleporter = [_random_end_pos] call XfMissionRandomStartTeleporter;
	// If no spot found, we get back an empty position.
	if (count (_teleporter select 0) > 0) then {
		[false,["chapter1_start_position",(_teleporter select 0), "ICON", "ColorBlue", [1,1],"",(_teleporter select 1),"hd_start","",1]] call XfMissionMarker;
	};
	
	["StopConvoy","Stop the Convoy", Format["A convoy carrying weapons for our enemies is travelling across the country.<br />You need to intercept the convoy before it reaches its destination!<br />It is travelling from %1 to %2.<br />Good luck!", _random_town_name,_random_end_name],"",[],"Created"] call XfMissionTask;
};

XfMissionChapterSuccess={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSuccess","Starting"];
	DM_Mission_Chapter_Success = 1;
};

XfMissionChapterFailure={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterFailure","Starting"];
	"You tried but failed... you'll do better next time." call XfMissionMessageToAll;
	DM_Mission_Chapter_Success = -1;
};

// Self-explanatory
XfMissionChapterCleanUp={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterCleanUp","Starting"];
	// Giving an empty position places the teleporter back to the hangar, closing the hangar.
	[[],0] call XfMissionPlaceStartTeleporter;
	[] call XfMissionCleanMarkers;
	[] call XfMissionCleanTriggers;
	[] call XfMissionCleanTasks;
};

DM_Mission_Chapter_Compiled = true;